{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--2019-07-05 04:30:40--  https://storage.googleapis.com/bert_models/2018_10_18/uncased_L-12_H-768_A-12.zip\n",
      "Resolving storage.googleapis.com (storage.googleapis.com)... 172.217.194.128, 2404:6800:4003:c00::80\n",
      "Connecting to storage.googleapis.com (storage.googleapis.com)|172.217.194.128|:443... connected.\n",
      "HTTP request sent, awaiting response... 200 OK\n",
      "Length: 407727028 (389M) [application/zip]\n",
      "Saving to: ‘uncased_L-12_H-768_A-12.zip’\n",
      "\n",
      "uncased_L-12_H-768_ 100%[===================>] 388.84M  56.7MB/s    in 7.7s    \n",
      "\n",
      "2019-07-05 04:30:48 (50.4 MB/s) - ‘uncased_L-12_H-768_A-12.zip’ saved [407727028/407727028]\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# !wget https://storage.googleapis.com/bert_models/2018_10_18/uncased_L-12_H-768_A-12.zip\n",
    "# !unzip uncased_L-12_H-768_A-12.zip"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "total 422M\r\n",
      "-rw-r--r-- 1 husein husein  313 Oct 18  2018 bert_config.json\r\n",
      "-rw-r--r-- 1 husein husein 421M Oct 18  2018 bert_model.ckpt.data-00000-of-00001\r\n",
      "-rw-r--r-- 1 husein husein 8.4K Oct 18  2018 bert_model.ckpt.index\r\n",
      "-rw-r--r-- 1 husein husein 884K Oct 18  2018 bert_model.ckpt.meta\r\n",
      "-rw-r--r-- 1 husein husein 227K Oct 18  2018 vocab.txt\r\n"
     ]
    }
   ],
   "source": [
    "!ls -lh uncased_L-12_H-768_A-12"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'attention_probs_dropout_prob': 0.1,\n",
       " 'hidden_act': 'gelu',\n",
       " 'hidden_dropout_prob': 0.1,\n",
       " 'hidden_size': 768,\n",
       " 'initializer_range': 0.02,\n",
       " 'intermediate_size': 3072,\n",
       " 'max_position_embeddings': 512,\n",
       " 'num_attention_heads': 12,\n",
       " 'num_hidden_layers': 12,\n",
       " 'type_vocab_size': 2,\n",
       " 'vocab_size': 30522}"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import json\n",
    "\n",
    "with open('uncased_L-12_H-768_A-12/bert_config.json') as fopen:\n",
    "    config = json.load(fopen)\n",
    "config"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "config['num_hidden_layers'] = 6\n",
    "with open('6_bert_config.json', 'w') as fopen:\n",
    "    json.dump(config, fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/husein/.local/lib/python3.6/site-packages/sklearn/cross_validation.py:41: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This module will be removed in 0.20.\n",
      "  \"This module will be removed in 0.20.\", DeprecationWarning)\n"
     ]
    }
   ],
   "source": [
    "from utils import *\n",
    "import tensorflow as tf\n",
    "from sklearn.cross_validation import train_test_split\n",
    "import time\n",
    "import random\n",
    "import os"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['negative', 'positive']\n",
      "10662\n",
      "10662\n"
     ]
    }
   ],
   "source": [
    "trainset = sklearn.datasets.load_files(container_path = 'data', encoding = 'UTF-8')\n",
    "trainset.data, trainset.target = separate_dataset(trainset,1.0)\n",
    "print (trainset.target_names)\n",
    "print (len(trainset.data))\n",
    "print (len(trainset.target))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "BERT_VOCAB = 'uncased_L-12_H-768_A-12/vocab.txt'\n",
    "BERT_INIT_CHKPNT = 'uncased_L-12_H-768_A-12/bert_model.ckpt'\n",
    "BERT_CONFIG = '6_bert_config.json'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "import bert\n",
    "from bert import run_classifier\n",
    "from bert import optimization\n",
    "from bert import tokenization\n",
    "from bert import modeling"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "tokenization.validate_case_matches_checkpoint(True,BERT_INIT_CHKPNT)\n",
    "tokenizer = tokenization.FullTokenizer(\n",
    "      vocab_file=BERT_VOCAB, do_lower_case=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "MAX_SEQ_LENGTH = 100"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 10662/10662 [00:03<00:00, 3454.79it/s]\n"
     ]
    }
   ],
   "source": [
    "from tqdm import tqdm\n",
    "\n",
    "input_ids, input_masks, segment_ids = [], [], []\n",
    "\n",
    "for text in tqdm(trainset.data):\n",
    "    tokens_a = tokenizer.tokenize(text)\n",
    "    if len(tokens_a) > MAX_SEQ_LENGTH - 2:\n",
    "        tokens_a = tokens_a[:(MAX_SEQ_LENGTH - 2)]\n",
    "    tokens = [\"[CLS]\"] + tokens_a + [\"[SEP]\"]\n",
    "    segment_id = [0] * len(tokens)\n",
    "    input_id = tokenizer.convert_tokens_to_ids(tokens)\n",
    "    input_mask = [1] * len(input_id)\n",
    "    padding = [0] * (MAX_SEQ_LENGTH - len(input_id))\n",
    "    input_id += padding\n",
    "    input_mask += padding\n",
    "    segment_id += padding\n",
    "    \n",
    "    input_ids.append(input_id)\n",
    "    input_masks.append(input_mask)\n",
    "    segment_ids.append(segment_id)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [],
   "source": [
    "bert_config = modeling.BertConfig.from_json_file(BERT_CONFIG)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['ra',\n",
       " '##ra',\n",
       " 'av',\n",
       " '##is',\n",
       " 'intelligent',\n",
       " 'romantic',\n",
       " 'comedy',\n",
       " 'actual',\n",
       " 'ideas',\n",
       " 'mind']"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tokenizer.tokenize(trainset.data[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "epoch = 5\n",
    "batch_size = 3\n",
    "warmup_proportion = 0.1\n",
    "num_train_steps = int(len(input_ids) / batch_size * epoch)\n",
    "num_warmup_steps = int(num_train_steps * warmup_proportion)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Model:\n",
    "    def __init__(\n",
    "        self,\n",
    "        dimension_output,\n",
    "        learning_rate = 2e-5,\n",
    "    ):\n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.segment_ids = tf.placeholder(tf.int32, [None, None])\n",
    "        self.input_masks = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None])\n",
    "        \n",
    "        model = modeling.BertModel(\n",
    "            config=bert_config,\n",
    "            is_training=True,\n",
    "            input_ids=self.X,\n",
    "            input_mask=self.input_masks,\n",
    "            token_type_ids=self.segment_ids,\n",
    "            use_one_hot_embeddings=False)\n",
    "        \n",
    "        output_layer = model.get_pooled_output()\n",
    "        self.logits = tf.layers.dense(output_layer, dimension_output)\n",
    "        \n",
    "        self.cost = tf.reduce_mean(\n",
    "            tf.nn.sparse_softmax_cross_entropy_with_logits(\n",
    "                logits = self.logits, labels = self.Y\n",
    "            )\n",
    "        )\n",
    "        \n",
    "        self.optimizer = optimization.create_optimizer(self.cost, learning_rate, \n",
    "                                                       num_train_steps, num_warmup_steps, False)\n",
    "        correct_pred = tf.equal(\n",
    "            tf.argmax(self.logits, 1, output_type = tf.int32), self.Y\n",
    "        )\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [],
   "source": [
    "dimension_output = 2\n",
    "learning_rate = 2e-5\n",
    "\n",
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Model(\n",
    "    dimension_output,\n",
    "    learning_rate\n",
    ")\n",
    "\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[<tf.Variable 'bert/embeddings/word_embeddings:0' shape=(30522, 768) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/embeddings/token_type_embeddings:0' shape=(2, 768) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/embeddings/position_embeddings:0' shape=(512, 768) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/embeddings/LayerNorm/beta:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/embeddings/LayerNorm/gamma:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_0/attention/self/query/kernel:0' shape=(768, 768) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_0/attention/self/query/bias:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_0/attention/self/key/kernel:0' shape=(768, 768) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_0/attention/self/key/bias:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_0/attention/self/value/kernel:0' shape=(768, 768) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_0/attention/self/value/bias:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_0/attention/output/dense/kernel:0' shape=(768, 768) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_0/attention/output/dense/bias:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_0/attention/output/LayerNorm/beta:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_0/attention/output/LayerNorm/gamma:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_0/intermediate/dense/kernel:0' shape=(768, 3072) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_0/intermediate/dense/bias:0' shape=(3072,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_0/output/dense/kernel:0' shape=(3072, 768) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_0/output/dense/bias:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_0/output/LayerNorm/beta:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_0/output/LayerNorm/gamma:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_1/attention/self/query/kernel:0' shape=(768, 768) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_1/attention/self/query/bias:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_1/attention/self/key/kernel:0' shape=(768, 768) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_1/attention/self/key/bias:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_1/attention/self/value/kernel:0' shape=(768, 768) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_1/attention/self/value/bias:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_1/attention/output/dense/kernel:0' shape=(768, 768) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_1/attention/output/dense/bias:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_1/attention/output/LayerNorm/beta:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_1/attention/output/LayerNorm/gamma:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_1/intermediate/dense/kernel:0' shape=(768, 3072) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_1/intermediate/dense/bias:0' shape=(3072,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_1/output/dense/kernel:0' shape=(3072, 768) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_1/output/dense/bias:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_1/output/LayerNorm/beta:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_1/output/LayerNorm/gamma:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_2/attention/self/query/kernel:0' shape=(768, 768) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_2/attention/self/query/bias:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_2/attention/self/key/kernel:0' shape=(768, 768) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_2/attention/self/key/bias:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_2/attention/self/value/kernel:0' shape=(768, 768) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_2/attention/self/value/bias:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_2/attention/output/dense/kernel:0' shape=(768, 768) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_2/attention/output/dense/bias:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_2/attention/output/LayerNorm/beta:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_2/attention/output/LayerNorm/gamma:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_2/intermediate/dense/kernel:0' shape=(768, 3072) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_2/intermediate/dense/bias:0' shape=(3072,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_2/output/dense/kernel:0' shape=(3072, 768) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_2/output/dense/bias:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_2/output/LayerNorm/beta:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_2/output/LayerNorm/gamma:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_3/attention/self/query/kernel:0' shape=(768, 768) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_3/attention/self/query/bias:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_3/attention/self/key/kernel:0' shape=(768, 768) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_3/attention/self/key/bias:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_3/attention/self/value/kernel:0' shape=(768, 768) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_3/attention/self/value/bias:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_3/attention/output/dense/kernel:0' shape=(768, 768) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_3/attention/output/dense/bias:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_3/attention/output/LayerNorm/beta:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_3/attention/output/LayerNorm/gamma:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_3/intermediate/dense/kernel:0' shape=(768, 3072) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_3/intermediate/dense/bias:0' shape=(3072,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_3/output/dense/kernel:0' shape=(3072, 768) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_3/output/dense/bias:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_3/output/LayerNorm/beta:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_3/output/LayerNorm/gamma:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_4/attention/self/query/kernel:0' shape=(768, 768) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_4/attention/self/query/bias:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_4/attention/self/key/kernel:0' shape=(768, 768) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_4/attention/self/key/bias:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_4/attention/self/value/kernel:0' shape=(768, 768) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_4/attention/self/value/bias:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_4/attention/output/dense/kernel:0' shape=(768, 768) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_4/attention/output/dense/bias:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_4/attention/output/LayerNorm/beta:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_4/attention/output/LayerNorm/gamma:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_4/intermediate/dense/kernel:0' shape=(768, 3072) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_4/intermediate/dense/bias:0' shape=(3072,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_4/output/dense/kernel:0' shape=(3072, 768) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_4/output/dense/bias:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_4/output/LayerNorm/beta:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_4/output/LayerNorm/gamma:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_5/attention/self/query/kernel:0' shape=(768, 768) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_5/attention/self/query/bias:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_5/attention/self/key/kernel:0' shape=(768, 768) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_5/attention/self/key/bias:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_5/attention/self/value/kernel:0' shape=(768, 768) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_5/attention/self/value/bias:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_5/attention/output/dense/kernel:0' shape=(768, 768) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_5/attention/output/dense/bias:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_5/attention/output/LayerNorm/beta:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_5/attention/output/LayerNorm/gamma:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_5/intermediate/dense/kernel:0' shape=(768, 3072) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_5/intermediate/dense/bias:0' shape=(3072,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_5/output/dense/kernel:0' shape=(3072, 768) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_5/output/dense/bias:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_5/output/LayerNorm/beta:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/encoder/layer_5/output/LayerNorm/gamma:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/pooler/dense/kernel:0' shape=(768, 768) dtype=float32_ref>,\n",
       " <tf.Variable 'bert/pooler/dense/bias:0' shape=(768,) dtype=float32_ref>,\n",
       " <tf.Variable 'dense/kernel:0' shape=(768, 2) dtype=float32_ref>,\n",
       " <tf.Variable 'dense/bias:0' shape=(2,) dtype=float32_ref>]"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tvars = tf.trainable_variables()\n",
    "tvars"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_assignment_map_from_checkpoint(tvars, init_checkpoint):\n",
    "    \"\"\"Compute the union of the current variables and checkpoint variables.\"\"\"\n",
    "    assignment_map = {}\n",
    "    initialized_variable_names = {}\n",
    "\n",
    "    name_to_variable = collections.OrderedDict()\n",
    "    for var in tvars:\n",
    "        name = var.name\n",
    "        m = re.match('^(.*):\\\\d+$', name)\n",
    "        if m is not None:\n",
    "            name = m.group(1)\n",
    "        name_to_variable[name] = var\n",
    "\n",
    "    init_vars = tf.train.list_variables(init_checkpoint)\n",
    "\n",
    "    assignment_map = collections.OrderedDict()\n",
    "    for x in init_vars:\n",
    "        (name, var) = (x[0], x[1])\n",
    "        if name not in name_to_variable:\n",
    "            continue\n",
    "        assignment_map[name] = name_to_variable[name]\n",
    "        initialized_variable_names[name] = 1\n",
    "        initialized_variable_names[name + ':0'] = 1\n",
    "\n",
    "    return (assignment_map, initialized_variable_names)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'bert/embeddings/LayerNorm/beta': 1,\n",
       " 'bert/embeddings/LayerNorm/beta:0': 1,\n",
       " 'bert/embeddings/LayerNorm/gamma': 1,\n",
       " 'bert/embeddings/LayerNorm/gamma:0': 1,\n",
       " 'bert/embeddings/position_embeddings': 1,\n",
       " 'bert/embeddings/position_embeddings:0': 1,\n",
       " 'bert/embeddings/token_type_embeddings': 1,\n",
       " 'bert/embeddings/token_type_embeddings:0': 1,\n",
       " 'bert/embeddings/word_embeddings': 1,\n",
       " 'bert/embeddings/word_embeddings:0': 1,\n",
       " 'bert/encoder/layer_0/attention/output/LayerNorm/beta': 1,\n",
       " 'bert/encoder/layer_0/attention/output/LayerNorm/beta:0': 1,\n",
       " 'bert/encoder/layer_0/attention/output/LayerNorm/gamma': 1,\n",
       " 'bert/encoder/layer_0/attention/output/LayerNorm/gamma:0': 1,\n",
       " 'bert/encoder/layer_0/attention/output/dense/bias': 1,\n",
       " 'bert/encoder/layer_0/attention/output/dense/bias:0': 1,\n",
       " 'bert/encoder/layer_0/attention/output/dense/kernel': 1,\n",
       " 'bert/encoder/layer_0/attention/output/dense/kernel:0': 1,\n",
       " 'bert/encoder/layer_0/attention/self/key/bias': 1,\n",
       " 'bert/encoder/layer_0/attention/self/key/bias:0': 1,\n",
       " 'bert/encoder/layer_0/attention/self/key/kernel': 1,\n",
       " 'bert/encoder/layer_0/attention/self/key/kernel:0': 1,\n",
       " 'bert/encoder/layer_0/attention/self/query/bias': 1,\n",
       " 'bert/encoder/layer_0/attention/self/query/bias:0': 1,\n",
       " 'bert/encoder/layer_0/attention/self/query/kernel': 1,\n",
       " 'bert/encoder/layer_0/attention/self/query/kernel:0': 1,\n",
       " 'bert/encoder/layer_0/attention/self/value/bias': 1,\n",
       " 'bert/encoder/layer_0/attention/self/value/bias:0': 1,\n",
       " 'bert/encoder/layer_0/attention/self/value/kernel': 1,\n",
       " 'bert/encoder/layer_0/attention/self/value/kernel:0': 1,\n",
       " 'bert/encoder/layer_0/intermediate/dense/bias': 1,\n",
       " 'bert/encoder/layer_0/intermediate/dense/bias:0': 1,\n",
       " 'bert/encoder/layer_0/intermediate/dense/kernel': 1,\n",
       " 'bert/encoder/layer_0/intermediate/dense/kernel:0': 1,\n",
       " 'bert/encoder/layer_0/output/LayerNorm/beta': 1,\n",
       " 'bert/encoder/layer_0/output/LayerNorm/beta:0': 1,\n",
       " 'bert/encoder/layer_0/output/LayerNorm/gamma': 1,\n",
       " 'bert/encoder/layer_0/output/LayerNorm/gamma:0': 1,\n",
       " 'bert/encoder/layer_0/output/dense/bias': 1,\n",
       " 'bert/encoder/layer_0/output/dense/bias:0': 1,\n",
       " 'bert/encoder/layer_0/output/dense/kernel': 1,\n",
       " 'bert/encoder/layer_0/output/dense/kernel:0': 1,\n",
       " 'bert/encoder/layer_1/attention/output/LayerNorm/beta': 1,\n",
       " 'bert/encoder/layer_1/attention/output/LayerNorm/beta:0': 1,\n",
       " 'bert/encoder/layer_1/attention/output/LayerNorm/gamma': 1,\n",
       " 'bert/encoder/layer_1/attention/output/LayerNorm/gamma:0': 1,\n",
       " 'bert/encoder/layer_1/attention/output/dense/bias': 1,\n",
       " 'bert/encoder/layer_1/attention/output/dense/bias:0': 1,\n",
       " 'bert/encoder/layer_1/attention/output/dense/kernel': 1,\n",
       " 'bert/encoder/layer_1/attention/output/dense/kernel:0': 1,\n",
       " 'bert/encoder/layer_1/attention/self/key/bias': 1,\n",
       " 'bert/encoder/layer_1/attention/self/key/bias:0': 1,\n",
       " 'bert/encoder/layer_1/attention/self/key/kernel': 1,\n",
       " 'bert/encoder/layer_1/attention/self/key/kernel:0': 1,\n",
       " 'bert/encoder/layer_1/attention/self/query/bias': 1,\n",
       " 'bert/encoder/layer_1/attention/self/query/bias:0': 1,\n",
       " 'bert/encoder/layer_1/attention/self/query/kernel': 1,\n",
       " 'bert/encoder/layer_1/attention/self/query/kernel:0': 1,\n",
       " 'bert/encoder/layer_1/attention/self/value/bias': 1,\n",
       " 'bert/encoder/layer_1/attention/self/value/bias:0': 1,\n",
       " 'bert/encoder/layer_1/attention/self/value/kernel': 1,\n",
       " 'bert/encoder/layer_1/attention/self/value/kernel:0': 1,\n",
       " 'bert/encoder/layer_1/intermediate/dense/bias': 1,\n",
       " 'bert/encoder/layer_1/intermediate/dense/bias:0': 1,\n",
       " 'bert/encoder/layer_1/intermediate/dense/kernel': 1,\n",
       " 'bert/encoder/layer_1/intermediate/dense/kernel:0': 1,\n",
       " 'bert/encoder/layer_1/output/LayerNorm/beta': 1,\n",
       " 'bert/encoder/layer_1/output/LayerNorm/beta:0': 1,\n",
       " 'bert/encoder/layer_1/output/LayerNorm/gamma': 1,\n",
       " 'bert/encoder/layer_1/output/LayerNorm/gamma:0': 1,\n",
       " 'bert/encoder/layer_1/output/dense/bias': 1,\n",
       " 'bert/encoder/layer_1/output/dense/bias:0': 1,\n",
       " 'bert/encoder/layer_1/output/dense/kernel': 1,\n",
       " 'bert/encoder/layer_1/output/dense/kernel:0': 1,\n",
       " 'bert/encoder/layer_2/attention/output/LayerNorm/beta': 1,\n",
       " 'bert/encoder/layer_2/attention/output/LayerNorm/beta:0': 1,\n",
       " 'bert/encoder/layer_2/attention/output/LayerNorm/gamma': 1,\n",
       " 'bert/encoder/layer_2/attention/output/LayerNorm/gamma:0': 1,\n",
       " 'bert/encoder/layer_2/attention/output/dense/bias': 1,\n",
       " 'bert/encoder/layer_2/attention/output/dense/bias:0': 1,\n",
       " 'bert/encoder/layer_2/attention/output/dense/kernel': 1,\n",
       " 'bert/encoder/layer_2/attention/output/dense/kernel:0': 1,\n",
       " 'bert/encoder/layer_2/attention/self/key/bias': 1,\n",
       " 'bert/encoder/layer_2/attention/self/key/bias:0': 1,\n",
       " 'bert/encoder/layer_2/attention/self/key/kernel': 1,\n",
       " 'bert/encoder/layer_2/attention/self/key/kernel:0': 1,\n",
       " 'bert/encoder/layer_2/attention/self/query/bias': 1,\n",
       " 'bert/encoder/layer_2/attention/self/query/bias:0': 1,\n",
       " 'bert/encoder/layer_2/attention/self/query/kernel': 1,\n",
       " 'bert/encoder/layer_2/attention/self/query/kernel:0': 1,\n",
       " 'bert/encoder/layer_2/attention/self/value/bias': 1,\n",
       " 'bert/encoder/layer_2/attention/self/value/bias:0': 1,\n",
       " 'bert/encoder/layer_2/attention/self/value/kernel': 1,\n",
       " 'bert/encoder/layer_2/attention/self/value/kernel:0': 1,\n",
       " 'bert/encoder/layer_2/intermediate/dense/bias': 1,\n",
       " 'bert/encoder/layer_2/intermediate/dense/bias:0': 1,\n",
       " 'bert/encoder/layer_2/intermediate/dense/kernel': 1,\n",
       " 'bert/encoder/layer_2/intermediate/dense/kernel:0': 1,\n",
       " 'bert/encoder/layer_2/output/LayerNorm/beta': 1,\n",
       " 'bert/encoder/layer_2/output/LayerNorm/beta:0': 1,\n",
       " 'bert/encoder/layer_2/output/LayerNorm/gamma': 1,\n",
       " 'bert/encoder/layer_2/output/LayerNorm/gamma:0': 1,\n",
       " 'bert/encoder/layer_2/output/dense/bias': 1,\n",
       " 'bert/encoder/layer_2/output/dense/bias:0': 1,\n",
       " 'bert/encoder/layer_2/output/dense/kernel': 1,\n",
       " 'bert/encoder/layer_2/output/dense/kernel:0': 1,\n",
       " 'bert/encoder/layer_3/attention/output/LayerNorm/beta': 1,\n",
       " 'bert/encoder/layer_3/attention/output/LayerNorm/beta:0': 1,\n",
       " 'bert/encoder/layer_3/attention/output/LayerNorm/gamma': 1,\n",
       " 'bert/encoder/layer_3/attention/output/LayerNorm/gamma:0': 1,\n",
       " 'bert/encoder/layer_3/attention/output/dense/bias': 1,\n",
       " 'bert/encoder/layer_3/attention/output/dense/bias:0': 1,\n",
       " 'bert/encoder/layer_3/attention/output/dense/kernel': 1,\n",
       " 'bert/encoder/layer_3/attention/output/dense/kernel:0': 1,\n",
       " 'bert/encoder/layer_3/attention/self/key/bias': 1,\n",
       " 'bert/encoder/layer_3/attention/self/key/bias:0': 1,\n",
       " 'bert/encoder/layer_3/attention/self/key/kernel': 1,\n",
       " 'bert/encoder/layer_3/attention/self/key/kernel:0': 1,\n",
       " 'bert/encoder/layer_3/attention/self/query/bias': 1,\n",
       " 'bert/encoder/layer_3/attention/self/query/bias:0': 1,\n",
       " 'bert/encoder/layer_3/attention/self/query/kernel': 1,\n",
       " 'bert/encoder/layer_3/attention/self/query/kernel:0': 1,\n",
       " 'bert/encoder/layer_3/attention/self/value/bias': 1,\n",
       " 'bert/encoder/layer_3/attention/self/value/bias:0': 1,\n",
       " 'bert/encoder/layer_3/attention/self/value/kernel': 1,\n",
       " 'bert/encoder/layer_3/attention/self/value/kernel:0': 1,\n",
       " 'bert/encoder/layer_3/intermediate/dense/bias': 1,\n",
       " 'bert/encoder/layer_3/intermediate/dense/bias:0': 1,\n",
       " 'bert/encoder/layer_3/intermediate/dense/kernel': 1,\n",
       " 'bert/encoder/layer_3/intermediate/dense/kernel:0': 1,\n",
       " 'bert/encoder/layer_3/output/LayerNorm/beta': 1,\n",
       " 'bert/encoder/layer_3/output/LayerNorm/beta:0': 1,\n",
       " 'bert/encoder/layer_3/output/LayerNorm/gamma': 1,\n",
       " 'bert/encoder/layer_3/output/LayerNorm/gamma:0': 1,\n",
       " 'bert/encoder/layer_3/output/dense/bias': 1,\n",
       " 'bert/encoder/layer_3/output/dense/bias:0': 1,\n",
       " 'bert/encoder/layer_3/output/dense/kernel': 1,\n",
       " 'bert/encoder/layer_3/output/dense/kernel:0': 1,\n",
       " 'bert/encoder/layer_4/attention/output/LayerNorm/beta': 1,\n",
       " 'bert/encoder/layer_4/attention/output/LayerNorm/beta:0': 1,\n",
       " 'bert/encoder/layer_4/attention/output/LayerNorm/gamma': 1,\n",
       " 'bert/encoder/layer_4/attention/output/LayerNorm/gamma:0': 1,\n",
       " 'bert/encoder/layer_4/attention/output/dense/bias': 1,\n",
       " 'bert/encoder/layer_4/attention/output/dense/bias:0': 1,\n",
       " 'bert/encoder/layer_4/attention/output/dense/kernel': 1,\n",
       " 'bert/encoder/layer_4/attention/output/dense/kernel:0': 1,\n",
       " 'bert/encoder/layer_4/attention/self/key/bias': 1,\n",
       " 'bert/encoder/layer_4/attention/self/key/bias:0': 1,\n",
       " 'bert/encoder/layer_4/attention/self/key/kernel': 1,\n",
       " 'bert/encoder/layer_4/attention/self/key/kernel:0': 1,\n",
       " 'bert/encoder/layer_4/attention/self/query/bias': 1,\n",
       " 'bert/encoder/layer_4/attention/self/query/bias:0': 1,\n",
       " 'bert/encoder/layer_4/attention/self/query/kernel': 1,\n",
       " 'bert/encoder/layer_4/attention/self/query/kernel:0': 1,\n",
       " 'bert/encoder/layer_4/attention/self/value/bias': 1,\n",
       " 'bert/encoder/layer_4/attention/self/value/bias:0': 1,\n",
       " 'bert/encoder/layer_4/attention/self/value/kernel': 1,\n",
       " 'bert/encoder/layer_4/attention/self/value/kernel:0': 1,\n",
       " 'bert/encoder/layer_4/intermediate/dense/bias': 1,\n",
       " 'bert/encoder/layer_4/intermediate/dense/bias:0': 1,\n",
       " 'bert/encoder/layer_4/intermediate/dense/kernel': 1,\n",
       " 'bert/encoder/layer_4/intermediate/dense/kernel:0': 1,\n",
       " 'bert/encoder/layer_4/output/LayerNorm/beta': 1,\n",
       " 'bert/encoder/layer_4/output/LayerNorm/beta:0': 1,\n",
       " 'bert/encoder/layer_4/output/LayerNorm/gamma': 1,\n",
       " 'bert/encoder/layer_4/output/LayerNorm/gamma:0': 1,\n",
       " 'bert/encoder/layer_4/output/dense/bias': 1,\n",
       " 'bert/encoder/layer_4/output/dense/bias:0': 1,\n",
       " 'bert/encoder/layer_4/output/dense/kernel': 1,\n",
       " 'bert/encoder/layer_4/output/dense/kernel:0': 1,\n",
       " 'bert/encoder/layer_5/attention/output/LayerNorm/beta': 1,\n",
       " 'bert/encoder/layer_5/attention/output/LayerNorm/beta:0': 1,\n",
       " 'bert/encoder/layer_5/attention/output/LayerNorm/gamma': 1,\n",
       " 'bert/encoder/layer_5/attention/output/LayerNorm/gamma:0': 1,\n",
       " 'bert/encoder/layer_5/attention/output/dense/bias': 1,\n",
       " 'bert/encoder/layer_5/attention/output/dense/bias:0': 1,\n",
       " 'bert/encoder/layer_5/attention/output/dense/kernel': 1,\n",
       " 'bert/encoder/layer_5/attention/output/dense/kernel:0': 1,\n",
       " 'bert/encoder/layer_5/attention/self/key/bias': 1,\n",
       " 'bert/encoder/layer_5/attention/self/key/bias:0': 1,\n",
       " 'bert/encoder/layer_5/attention/self/key/kernel': 1,\n",
       " 'bert/encoder/layer_5/attention/self/key/kernel:0': 1,\n",
       " 'bert/encoder/layer_5/attention/self/query/bias': 1,\n",
       " 'bert/encoder/layer_5/attention/self/query/bias:0': 1,\n",
       " 'bert/encoder/layer_5/attention/self/query/kernel': 1,\n",
       " 'bert/encoder/layer_5/attention/self/query/kernel:0': 1,\n",
       " 'bert/encoder/layer_5/attention/self/value/bias': 1,\n",
       " 'bert/encoder/layer_5/attention/self/value/bias:0': 1,\n",
       " 'bert/encoder/layer_5/attention/self/value/kernel': 1,\n",
       " 'bert/encoder/layer_5/attention/self/value/kernel:0': 1,\n",
       " 'bert/encoder/layer_5/intermediate/dense/bias': 1,\n",
       " 'bert/encoder/layer_5/intermediate/dense/bias:0': 1,\n",
       " 'bert/encoder/layer_5/intermediate/dense/kernel': 1,\n",
       " 'bert/encoder/layer_5/intermediate/dense/kernel:0': 1,\n",
       " 'bert/encoder/layer_5/output/LayerNorm/beta': 1,\n",
       " 'bert/encoder/layer_5/output/LayerNorm/beta:0': 1,\n",
       " 'bert/encoder/layer_5/output/LayerNorm/gamma': 1,\n",
       " 'bert/encoder/layer_5/output/LayerNorm/gamma:0': 1,\n",
       " 'bert/encoder/layer_5/output/dense/bias': 1,\n",
       " 'bert/encoder/layer_5/output/dense/bias:0': 1,\n",
       " 'bert/encoder/layer_5/output/dense/kernel': 1,\n",
       " 'bert/encoder/layer_5/output/dense/kernel:0': 1,\n",
       " 'bert/pooler/dense/bias': 1,\n",
       " 'bert/pooler/dense/bias:0': 1,\n",
       " 'bert/pooler/dense/kernel': 1,\n",
       " 'bert/pooler/dense/kernel:0': 1}"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "assignment_map, initialized_variable_names = get_assignment_map_from_checkpoint(tvars, \n",
    "                                                                                BERT_INIT_CHKPNT)\n",
    "initialized_variable_names"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:tensorflow:Restoring parameters from uncased_L-12_H-768_A-12/bert_model.ckpt\n"
     ]
    }
   ],
   "source": [
    "saver = tf.train.Saver(var_list = assignment_map)\n",
    "saver.restore(sess, BERT_INIT_CHKPNT)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_input_ids, test_input_ids, train_input_masks, test_input_masks, train_segment_ids, test_segment_ids, train_Y, test_Y = train_test_split(\n",
    "    input_ids, input_masks, segment_ids, trainset.target, test_size = 0.2\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 2843/2843 [07:51<00:00,  6.03it/s, accuracy=0.667, cost=1.06] \n",
      "test minibatch loop: 100%|██████████| 711/711 [00:23<00:00, 30.54it/s, accuracy=1, cost=0.0589]   \n",
      "train minibatch loop:   0%|          | 1/2843 [00:00<08:03,  5.88it/s, accuracy=1, cost=0.0483]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 0, pass acc: 0.000000, current acc: 0.765588\n",
      "time taken: 494.7259032726288\n",
      "epoch: 0, training loss: 0.679368, training acc: 0.699144, valid loss: 0.647409, valid acc: 0.765588\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 2843/2843 [07:51<00:00,  6.04it/s, accuracy=0.667, cost=1.37] \n",
      "test minibatch loop: 100%|██████████| 711/711 [00:23<00:00, 30.81it/s, accuracy=1, cost=0.175]    \n",
      "train minibatch loop:   0%|          | 1/2843 [00:00<07:56,  5.97it/s, accuracy=1, cost=0.0641]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 1, pass acc: 0.765588, current acc: 0.776371\n",
      "time taken: 494.1690831184387\n",
      "epoch: 1, training loss: 0.536140, training acc: 0.850745, valid loss: 0.849323, valid acc: 0.776371\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 2843/2843 [07:51<00:00,  6.02it/s, accuracy=0.667, cost=0.859]\n",
      "test minibatch loop: 100%|██████████| 711/711 [00:23<00:00, 30.90it/s, accuracy=1, cost=0.00422]  \n",
      "train minibatch loop:   0%|          | 1/2843 [00:00<07:59,  5.93it/s, accuracy=1, cost=0.000441]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "time taken: 494.4359619617462\n",
      "epoch: 2, training loss: 0.324216, training acc: 0.929417, valid loss: 1.227605, valid acc: 0.773558\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 2843/2843 [07:50<00:00,  6.04it/s, accuracy=1, cost=0.00232]  \n",
      "test minibatch loop: 100%|██████████| 711/711 [00:23<00:00, 30.50it/s, accuracy=1, cost=0.000247] \n",
      "train minibatch loop:   0%|          | 1/2843 [00:00<07:59,  5.93it/s, accuracy=1, cost=2.95e-5]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "time taken: 494.08778500556946\n",
      "epoch: 3, training loss: 0.158032, training acc: 0.968109, valid loss: 1.683650, valid acc: 0.748242\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 2843/2843 [07:50<00:00,  6.06it/s, accuracy=1, cost=0.000403] \n",
      "test minibatch loop: 100%|██████████| 711/711 [00:22<00:00, 31.02it/s, accuracy=0.667, cost=2.24] "
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "time taken: 493.2808885574341\n",
      "epoch: 4, training loss: 0.088819, training acc: 0.982765, valid loss: 1.804691, valid acc: 0.773090\n",
      "\n",
      "break epoch:5\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "from tqdm import tqdm\n",
    "import time\n",
    "\n",
    "EARLY_STOPPING, CURRENT_CHECKPOINT, CURRENT_ACC, EPOCH = 3, 0, 0, 0\n",
    "\n",
    "while True:\n",
    "    lasttime = time.time()\n",
    "    if CURRENT_CHECKPOINT == EARLY_STOPPING:\n",
    "        print('break epoch:%d\\n' % (EPOCH))\n",
    "        break\n",
    "\n",
    "    train_acc, train_loss, test_acc, test_loss = 0, 0, 0, 0\n",
    "    pbar = tqdm(\n",
    "        range(0, len(train_input_ids), batch_size), desc = 'train minibatch loop'\n",
    "    )\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_input_ids))\n",
    "        batch_x = train_input_ids[i: index]\n",
    "        batch_masks = train_input_masks[i: index]\n",
    "        batch_segment = train_segment_ids[i: index]\n",
    "        batch_y = train_Y[i: index]\n",
    "        acc, cost, _ = sess.run(\n",
    "            [model.accuracy, model.cost, model.optimizer],\n",
    "            feed_dict = {\n",
    "                model.Y: batch_y,\n",
    "                model.X: batch_x,\n",
    "                model.segment_ids: batch_segment,\n",
    "                model.input_masks: batch_masks\n",
    "            },\n",
    "        )\n",
    "        assert not np.isnan(cost)\n",
    "        train_loss += cost\n",
    "        train_acc += acc\n",
    "        pbar.set_postfix(cost = cost, accuracy = acc)\n",
    "\n",
    "    pbar = tqdm(range(0, len(test_input_ids), batch_size), desc = 'test minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_input_ids))\n",
    "        batch_x = test_input_ids[i: index]\n",
    "        batch_masks = test_input_masks[i: index]\n",
    "        batch_segment = test_segment_ids[i: index]\n",
    "        batch_y = test_Y[i: index]\n",
    "        acc, cost = sess.run(\n",
    "            [model.accuracy, model.cost],\n",
    "            feed_dict = {\n",
    "                model.Y: batch_y,\n",
    "                model.X: batch_x,\n",
    "                model.segment_ids: batch_segment,\n",
    "                model.input_masks: batch_masks\n",
    "            },\n",
    "        )\n",
    "        test_loss += cost\n",
    "        test_acc += acc\n",
    "        pbar.set_postfix(cost = cost, accuracy = acc)\n",
    "\n",
    "    train_loss /= len(train_input_ids) / batch_size\n",
    "    train_acc /= len(train_input_ids) / batch_size\n",
    "    test_loss /= len(test_input_ids) / batch_size\n",
    "    test_acc /= len(test_input_ids) / batch_size\n",
    "\n",
    "    if test_acc > CURRENT_ACC:\n",
    "        print(\n",
    "            'epoch: %d, pass acc: %f, current acc: %f'\n",
    "            % (EPOCH, CURRENT_ACC, test_acc)\n",
    "        )\n",
    "        CURRENT_ACC = test_acc\n",
    "        CURRENT_CHECKPOINT = 0\n",
    "    else:\n",
    "        CURRENT_CHECKPOINT += 1\n",
    "        \n",
    "    print('time taken:', time.time() - lasttime)\n",
    "    print(\n",
    "        'epoch: %d, training loss: %f, training acc: %f, valid loss: %f, valid acc: %f\\n'\n",
    "        % (EPOCH, train_loss, train_acc, test_loss, test_acc)\n",
    "    )\n",
    "    EPOCH += 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'bert/model.ckpt'"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "saver = tf.train.Saver(tf.trainable_variables())\n",
    "saver.save(sess, 'bert/model.ckpt')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "total 258M\r\n",
      "-rw-rw-r-- 1 husein husein   77 Jul  5 06:47 checkpoint\r\n",
      "-rw-rw-r-- 1 husein husein 256M Jul  5 06:47 model.ckpt.data-00000-of-00001\r\n",
      "-rw-rw-r-- 1 husein husein 4.3K Jul  5 06:47 model.ckpt.index\r\n",
      "-rw-rw-r-- 1 husein husein 2.0M Jul  5 06:47 model.ckpt.meta\r\n"
     ]
    }
   ],
   "source": [
    "!ls -lh bert"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.3919239904988123"
      ]
     },
     "execution_count": 38,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "(421 - 256) / 421"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## We save 40% of space, accuracy drop around 3-5%"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
